import { REQUEST_SUCCEEDED_CODE,InteractiveTypeList } from "./constants";
import { UserMessageListItem, 
ChatUserInfo,
InteractiveMessageList,
InteractiveMessageData,
QuestionMessageList,
LabelItem, 
OfficialNewsListItem,
 UserInfo } from "./dataClass";
import { request } from "@/utils/request";
import {getUserMessageListKey,getInteractiveMessageListKey,getOfficeNewsListKey} from "@/common/storageKeys";
import {getUserMessageList,
getMyUserInfo,
getInteractiveMessageList,
getOfficalList,
getQuestionMessageList,
saveQuestionMessageList
} from "@/common/storageFunctions";

/**
   * 
   * @description 获取最新的个人信息
   * @param userId {用户的id} 
   * @returns {UserInfo}用户的详细信息
   */
export async function getUserinfo(userId:number){
    let res = await request({
      data: {
        method: 'GET',
        group: 'user',
        action: `${userId}/info`,
        data: {
          userId: userId,
        },
        header: {
          'content-type': 'application/x-www-form-urlencoded',// 默认值
          
        },
      }
    });
    
    if (res.data.code === REQUEST_SUCCEEDED_CODE) {
      return res.data.data as UserInfo
    } else {
      return 
    }
}


/**
   * @description 关注指定id的用户
   * @param userId {用户的id} 
   * @returns {boolean} 是否关注成功
   */
export async function followUser(userId:number) {
    let res = await request({
        data: {
            method: 'POST',
            group: 'social',
            action: `attention/${userId}`,
            data: {
                userId: userId
            },
            header: {
                'content-type': 'application/x-www-form-urlencoded',// 默认值
           
            },
        }
    });
    if (res.data.code === REQUEST_SUCCEEDED_CODE) {
        return true
    } else {
        console.log(res)
        return false
    }
}
/**
   * @description 取消关注指定id的用户
   * @param userId {用户的id} 
   * @returns {boolean} 是否取消关注成功
   */
export async function  cancelAttention(userId:number){
    let res = await request({
        data: {
            method: 'DELETE',
            group: 'social',
            action: `removeAttention/${userId}`,
            data: {
                userId: userId
            },
            header: {
                'content-type': 'application/x-www-form-urlencoded',// 默认值
            },
        }
    });
    if (res.data.code === REQUEST_SUCCEEDED_CODE) {
       return true
    } else {
        console.log(res)
        return false
    }
}
/**
   * @description 取消点赞动态
   * @param id 动态的id
   * @returns {boolean} 是否取消点赞成功
   */
export async function CancleLikeArticle(id:number) {
    let res = await request({
        data: {
            method: 'POST',
            group: 'activity',
            action: `${id}/like/remove`,
            data: {
                id:id
            },
            header: {
                'content-type': 'application/x-www-form-urlencoded',// 默认值
            },
        }
    });
	
    if (res.data.code === REQUEST_SUCCEEDED_CODE) {
        return true
    } else {
        return false
    }
}
/**
   * @description 点赞动态
   * @param id 动态的id
   * @returns {boolean} 是否点赞成功
   */
export async function LikeThisArtice(id:number) {
   
    let res = await request({
        data: {
            method: 'POST',
            group: 'activity',
            action: `${id}/like`,
            data: {
                id: id
            },
            header: {
                'content-type': 'application/x-www-form-urlencoded',// 默认值
            },
        }
    });
	console.log(res.data)
    if (res.data.code === REQUEST_SUCCEEDED_CODE) {
        return true
    } else {
        return false
    }
}
/**
   * @description 获取指定id用户的在线状态
   * @param userId 用户的id
   * @returns {boolean} 在线状态
   */
export async function GetonlineState(userId:number){
    let res = await request({
        data: {
            method: 'GET',
            group: 'message',
            action: `onlineState`,
            data: {
                userId: userId
            },
            header: {
                'content-type': 'application/x-www-form-urlencoded',// 默认值
            },
        }
    });
    if (res.data.code === REQUEST_SUCCEEDED_CODE) {
        
        return res.data.data as boolean
    } else {
        return false
    }
}
/**
   * @description 删除我的动态
   * @param id 动态的id
   * @returns {boolean} 是否删除成功
   */
export async function deleteMyArticle(id) {
    let res = await request({
      data: {
        method: 'DELETE',
        group: 'activity',
        action: `${id}/delete`,
        data: {
          id: id
        },
        header: {
          'content-type': 'application/x-www-form-urlencoded',// 默认值

        },
      }
    });
    if (res.data.code === REQUEST_SUCCEEDED_CODE) {
        return true
    } else {
        return false
    }
  }

/**
   * @description 获取动态标签
   * @param page 页数
   */
export async  function getHotLabels(page: number = 1) {
    let res = await request({
      data: {
        method: 'GET',
        group: 'activity',
        action: 'label/list',
        data: {
          page: page
        },
        header: {
          'content-type': 'application/x-www-form-urlencoded', // 默认值
        },
      }
    });
    if (res.data.code === REQUEST_SUCCEEDED_CODE) {
      let Labels: LabelItem[] = res.data.data.list
      return Labels
    } else {
      return []
    }
  }
/**
 * @description 获取邀请码
 * @returns {string}
 */
export  async function getInviteUserCode():Promise<string>{
	let res = await request({
		data: {
		  method: 'GET',
		  group: 'user',
		  action: 'invite',
		  data: {
		  },
		  header: {
			'content-type': 'application/x-www-form-urlencoded', // 默认值
		  },
		}
	  });
	if(res.data.code===REQUEST_SUCCEEDED_CODE){
	   return res.data.data
	}else{
	   return ''
	}
}
/**
 * @function 获取并处理消息列表
 * @param userId 用户的id
 * @returns {Promise<UserMessageListItem[]>}
 */
export async function getAndHandleUserMessageList(userId: number): Promise<UserMessageListItem[]> {
  //未读消息列表
  let unReadList = await getUnReadUser()
  console.log("unReadList",unReadList)
  //聊天用户id列表,用于获取最新信息
  let chatUsersId: number[] = []
  //聊天用户列表
  let userMessageList: UserMessageListItem[] = []
  //获取缓存的聊天信息
  let beforeUsermessageList = await getUserMessageList(userId)
  beforeUsermessageList.forEach((item) => {
	let hava_data = false
	//先判断是否有未读消息，如果有了就不加入
	for (let i = 0; i < unReadList.length; i++) {
	  if (unReadList[i].userId == item.userId) {
		hava_data = true 
		break
	  }
	}
	if (!hava_data) {
	  chatUsersId.push(item.userId)
	  userMessageList.push(item)
	}
  })
  //获取最新的用户信息(头像和用户名)，循环遍历并加入
  let userInfos = await updateUserInfo(chatUsersId)
  for (let i = 0; i < userInfos.length; i++) {
	//一般来说是按照顺序一一对应的，如果不是则循环遍历一下
	if (userInfos[i].id == userMessageList[i].userId) {
	  userMessageList[i].avatar = userInfos[i].avatar
	  userMessageList[i].username = userInfos[i].username
	  userMessageList[i].online = userInfos[i].online
	} else {
	  for (let j = 0; j < userMessageList.length; j++) {
		if (userInfos[i].id == userMessageList[j].userId) {
		  userMessageList[j].avatar = userInfos[i].avatar
		  userMessageList[j].username = userInfos[i].username
		  userMessageList[j].online = userInfos[i].online
		  break
		}
	  }
	}
  }
  userMessageList = userMessageList.concat(unReadList)//将两个列表合在一起
  console.log("userMessageList",userMessageList)
  let storageKey = getUserMessageListKey(userId)
  uni.setStorage({ key: storageKey, data: userMessageList })//合并完后存储
  return userMessageList
}
/**
 * @description 更新用户信息
 * @returns {Promise<ChatUserInfo[]>}
 */
export async function updateUserInfo (userIds: number[]):Promise<ChatUserInfo[]> {
	if (!userIds || userIds.length <= 0) {
	  return []
	}
	let res = await request({
	  data: {
		method: 'GET',
		group: 'message',
		action: 'users/info',
		data: {
		  userIds: userIds
		},
		header: {
		  'content-type': 'application/x-www-form-urlencoded' // 默认值
		},
	  }
	});
	let userInfos: ChatUserInfo[] = []
	if (res.data.code === REQUEST_SUCCEEDED_CODE) {
	  userInfos = res.data.data as ChatUserInfo[]
	} else {
	  console.log(res.data)
	}
	return userInfos
}			
/**
 * @description 获取未读的消息列表
 * @returns {Promise<UserMessageListItem[]>}
 */
export async function getUnReadUser():Promise<UserMessageListItem[]> {
	let messageList: UserMessageListItem[] = []
	try {
	  let res = await request({
		data: {
		  method: 'GET',
		  group: 'message',
		  action: 'unRead/user',
		  data: {

		  },
		  header: {
			'content-type': 'application/x-www-form-urlencoded' // 默认值
		  },
		}
	  });

	  if (res.data.code === REQUEST_SUCCEEDED_CODE) {
		messageList = res.data.data as UserMessageListItem[]

	  } else {
		console.log(`getUnReadUser_error:${res.data}`)

	  }
	} catch {

	}
	return messageList
  }

/**
 * @function 获取并处理互动消息
 * @param userId 用户的Id
 * @returns {Promise<number>}
 */
export async function getAndHandleInteractiveMessageList(userId: number): Promise<number> {
  let unreadSum = 0
  let unreads = await getUnReadInteractiveMessage()
  // 保存之前的未读消息总数
  unreadSum = unreads.length
  
  for(let i = 0;i<InteractiveTypeList.length;i++){
	  let interactiveList = await getInteractiveMessageList(userId,InteractiveTypeList[i])
	  unreadSum = interactiveList.unreadSum+unreadSum
  }
  
  unreads.forEach(async (item)=>{
	  let INTERACTIVE_MESSAGE_LIST = getInteractiveMessageListKey(userId,item.type)
	  let interactiveList = await getInteractiveMessageList(userId,item.type)
	  interactiveList.data=[item].concat(interactiveList.data)
	  interactiveList.unreadSum = interactiveList.unreadSum+1
	  uni.setStorage({ key: INTERACTIVE_MESSAGE_LIST, data: interactiveList })
  })
  return unreadSum
}

/**
 * @function 获取未读的互动信息
 * @returns {Promise<InteractiveMessageData[]>}
 */
export async function getUnReadInteractiveMessage():Promise<InteractiveMessageData[]> {
	let res = await request({
	  data: {
		method: 'GET',
		group: 'message',
		action: 'interactive/unread',
		data: {

		},
		header: {
		  'content-type': 'application/x-www-form-urlencoded' // 默认值
		},
	  }
	});
	if (res.data.code === REQUEST_SUCCEEDED_CODE) {
	  let unreads = res.data.data as InteractiveMessageData[]
	  return unreads
	} else {
	  return []
	}
  }
/**
 * @function 获取并处理官方消息
 * @param userId 用户的Id
 * @returns {Promise<OfficialNewsListItem[]>}
 */
export async function getAndHandOfficialNewsList(userId: number): Promise<OfficialNewsListItem[]> {
  //未读消息列表
  let unReadNewsList = await getUnReadOfficialNews()
  let beforeOfficialNewsList = await getOfficalList(userId)
  let officialNewsList: OfficialNewsListItem[] = []
  beforeOfficialNewsList.forEach((item, index) => {
    let hava_data = false
    //先判断是否有未读消息，如果有了就不加入
    for (let i = 0; i < unReadNewsList.length; i++) {
      if (unReadNewsList[i].type == item.type) {
        hava_data = true
        break
      }
    }
    if (!hava_data) {
      officialNewsList.push(item)
    }
  })
  let OFFICE_NEWS_LIST = getOfficeNewsListKey(userId)
  officialNewsList = officialNewsList.concat(unReadNewsList)
  await uni.setStorage({
    key: OFFICE_NEWS_LIST,
    data: officialNewsList
  })
  return officialNewsList
}
/**
 * @description 获取未读的官方消息
 * @returns {Promise<OfficialNewsListItem[]>}
 */
export async function getUnReadOfficialNews(): Promise<OfficialNewsListItem[]> {
  let res = await request({
    data: {
      method: 'GET',
      group: 'message',
      action: 'official/unread/list',
      data: {
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
    }
  });
  if (res.data.code === REQUEST_SUCCEEDED_CODE) {
    let officialNewsList = res.data.data
    return officialNewsList
  } else {
    return []
  }
}
/**
 * @function 获取并处理问题模块的消息
 * @param userId 用户的Id
 * @returns {Promise<QuestionMessageList>}
 */
export async function getAndHandQuestionMessageList(userId: number): Promise<QuestionMessageList> {
	let beforeQuetionsMessageList = await getQuestionMessageList(userId)
	let newQuestionMessageList = await getUnreadQuestionNotices(1)
	if(newQuestionMessageList.length<1){
		return beforeQuetionsMessageList
	}else{
		let quetionsMessageList = {
			unreadSum:beforeQuetionsMessageList.unreadSum+newQuestionMessageList.length,
			data:newQuestionMessageList.concat(beforeQuetionsMessageList.data)
		}
		saveQuestionMessageList(userId,quetionsMessageList)
		return quetionsMessageList
	}
}
 
/**
 * @description 获取当前登录用户未读问题通知
 * @param {startPage} number 起始页
 * @return 
 */
export async function getUnreadQuestionNotices(page: number) {
	let res = await request({
	  data: {
		modular:'dhy',
		method: 'GET',
		group: 'helping',
		action: `unread_notices`,
		data: {
		  startPage: page,
		  pageSize:50
		},
		header: {
		  'content-type': 'application/x-www-form-urlencoded',// 默认值
		},
	  }
	});
	
	if (res.data.code === REQUEST_SUCCEEDED_CODE) {
	  return res.data.data.data
	} else {
	  return []
	}
  }

/**
 * @description 评论动态
 * @param {number} id 动态的id
 * @param {string} content 评论内容
 * @param {number} 成功返回id 失败返回-1
 */
export async function commentActivity(id: number, content: string, type: number) {
	let res = await request({
		data: {
			method: 'POST',
			group: 'activity',
			action: `${id}/comment`,
			data: {
				id: id,
				content: content,
				type: type
			},
			header: {
				'content-type': 'application/x-www-form-urlencoded', // 默认值
			},
		}
	});
	if (res.data.code === REQUEST_SUCCEEDED_CODE) {
		return res.data.data
	} else {
		return -1
	}
}
/**
 * @description 回复评论
 * @param id 评论的Id
 * @param content 回复内容
 * @param type 回复类型
 * @param toUserId 对象的Id 为0时不回复任何人 为-1时回复匿名用户
 * @return {number} 成功返回id 失败返回-1
 */
export async function ReplyComments(id: number, content: string, type: number, toUserId: number = 0) {
	  let res = await request({
		data: {
		  method: 'POST',
		  group: 'activity/comment',
		  action: `${id}/response`,
		  data: {
			id: id,
			content: content,
			toUserId: toUserId,
			type: type
		  },
		  header: {
			'content-type': 'application/x-www-form-urlencoded',// 默认值
		  },
		}
	  });
	  
	  if (res.data.code === REQUEST_SUCCEEDED_CODE) {
		return res.data.data
		} else {
			return -1
		}
}
/**
 * @description 删除评论
 * @param {number} id 评论的id
 * @return {boolean} 成功返回true 失败返回false
 */
export async function DeleteComments(id:number) {
	let res = await request({
	  data: {
		method: 'DELETE',
		group: 'activity/comment',
		action: `${id}/delete`,
		data: {
		  id: id
		},
		header: {
		  'content-type': 'application/x-www-form-urlencoded',// 默认值
		},
	  }
	});
	if (res.data.code === REQUEST_SUCCEEDED_CODE) {
	  return true
	} else {
	  return false
	}
}
/**
 * @description 删除回复
 * @param {number} id 回复的id
 * @return {boolean} 成功返回true 失败返回false
 */
export async function DeleteReply(id: number) {
	let res = await request({
	  data: {
		method: 'DELETE',
		group: 'activity/comment',
		action: `response/${id}/delete`,
		data: {
		  id: id
		},
		header: {
		  'content-type': 'application/x-www-form-urlencoded',// 默认值
		},
	  }
	});
	if (res.data.code === REQUEST_SUCCEEDED_CODE) {
	  return true
	} else {
	  return false
	}
  }
/**
 * @description 删除问题
 * @param {number} id 问题的id
 * @return {boolean} 成功返回true 失败返回false
 */
export async function deleteQuestion(id: number) {
	let res = await request({
	  data: {
		modular:'dhy',
		method: 'DELETE',
		group: 'helping',
		action: `logicDelIssue`,
		data: {
		  issue_id: id
		},
		header: {
		  'content-type': 'application/x-www-form-urlencoded',// 默认值
		},
	  }
	});
	if (res.data.code === REQUEST_SUCCEEDED_CODE) {
	  return true
	} else {
	  return false
	}
  }
/**
 * @description 点赞/关注问题
 * @param {number} id 问题的id
 * @return {boolean} 成功返回true 失败返回false
 */
export async function likeQuestion(id: number) {
	let res = await request({
	  data: {
		modular:'dhy',
		method: 'POST',
		group: 'helping',
		action: `likeIssue`,
		data: {
		  issue_id: id
		},
		header: {
		  'content-type': 'application/x-www-form-urlencoded',// 默认值
		},
	  }
	});
	if (res.data.code === REQUEST_SUCCEEDED_CODE) {
	  return true
	} else {
		if(res.data.errMsg==="请勿重复点赞"){
			return true 
		}else{
			return false
		}
	  
	}
  }
/**
 * @description 取消点赞/关注问题
 * @param {number} id 问题的id
 * @return {boolean} 成功返回true 失败返回false
 */
export async function cancelLikeQuestion(id: number) {
	let res = await request({
	  data: {
		modular:'dhy',
		method: 'DELETE',
		group: 'helping',
		action: `likeIssue`,
		data: {
		  issue_id: id
		},
		header: {
		  'content-type': 'application/x-www-form-urlencoded',// 默认值
		},
	  }
	});
	if (res.data.code === REQUEST_SUCCEEDED_CODE) {
	  return true
	} else {
		
	  return false
	}
  }
/**
 * @description 删除回答
 * @param {number} comment_id 问题的id
 * @return {boolean} 成功返回true 失败返回false
 */
export async function deleteAnswer(issue_id:number,comment_id: number) {
	let res = await request({
	  data: {
		modular:'dhy',
		method: 'DELETE',
		group: 'helping',
		action: `logicDelComment`,
		data: {
		  issue_id,
		  comment_id
		},
		header: {
		  'content-type': 'application/x-www-form-urlencoded',// 默认值
		},
	  }
	});
	if (res.data.code === REQUEST_SUCCEEDED_CODE) {
	  return true
	} else {
	  return false
	}
}
/**
 * @description 点赞回答
 * @param {number} id 回答的id
 * @return {boolean} 成功返回true 失败返回false
 */
export async function likeAnwser(id: number) {
	let res = await request({
	  data: {
		modular:'dhy',
		method: 'POST',
		group: 'helping',
		action: `likeComment`,
		data: {
		  comment_id: id
		},
		header: {
		  'content-type': 'application/x-www-form-urlencoded',// 默认值
		},
	  }
	});
	if (res.data.code === REQUEST_SUCCEEDED_CODE) {
	  return true
	} else {
		if(res.data.errMsg==="请勿重复点赞"){
			return true 
		}else{
			return false
		}
	  
	}
  }
/**
 * @description 取消点赞答案
 * @param {number} id 答案的id
 * @return {boolean} 成功返回true 失败返回false
 */
export async function cancelLikeAnwser(id: number) {
	let res = await request({
	  data: {
		modular:'dhy',
		method: 'DELETE',
		group: 'helping',
		action: `likeComment`,
		data: {
		  comment_id : id
		},
		header: {
		  'content-type': 'application/x-www-form-urlencoded',// 默认值
		},
	  }
	});
	if (res.data.code === REQUEST_SUCCEEDED_CODE) {
	  return true
	} else {
	  return false
	}
}
/**
 * @description 评论回答
 * @param {number} issueId 问题的id
 * @param {number} answerId 回答的id
 * @param {string} content 评论内容
 * @param {number} 成功返回id 失败返回-1
 */
export async function commentAnswer(issueId:number,answerId: number, content: string, type: number) {
	let res = await request({
		data: {
			modular:'dhy',
			method: 'POST',
			group: 'helping',
			action: `sonComment`,
			data: {
				issue_id:issueId,
				father_comment_id: answerId,
				content: content,
				type: type
			},
			header: {
				'content-type': 'application/x-www-form-urlencoded', // 默认值
			},
		}
	});
	if (res.data.code === REQUEST_SUCCEEDED_CODE) {
		return res.data.data
	} else {
		return -1
	}
}
/**
 * @description 回复回答的评论
 * @param {number} issueId 问题的id
 * @param id 评论的Id
 * @param content 回复内容
 * @param type 回复类型
 * @param toUserId 对象的Id 为0时不回复任何人 为-1时回复匿名用户
 * @return {number} 成功返回id 失败返回-1
 */
export async function ReplyAnswerComments(commentId: number, content: string, type: number, toUserId: number = 0,
grant_son_comment_id:number= 0) {
	  let res = await request({
		data: {
		  modular:'dhy',
		  method: 'POST',
		  group: 'helping',
		  action: `grantSonComment`,
		  data: {
			son_comment_id: commentId,
			content: content,
			to_user_id: toUserId,
			grant_son_comment_id
		  },
		  header: {
			'content-type': 'application/x-www-form-urlencoded',// 默认值
		  },
		}
	  });
	  
	  if (res.data.code === REQUEST_SUCCEEDED_CODE) {
		return res.data.data
		} else {
			return -1
		}
}

/**
 * @description 点赞回答的评论
 * @param {number} son_comment_id 评论的id
 * @return {boolean} 成功返回true 失败返回false
 */
export async function likeAnwserComment(son_comment_id: number) {
	let res = await request({
	  data: {
		modular:'dhy',
		method: 'POST',
		group: 'helping',
		action: `likeSonComment`,
		data: {
		  son_comment_id
		},
		header: {
		  'content-type': 'application/x-www-form-urlencoded',// 默认值
		},
	  }
	});
	if (res.data.code === REQUEST_SUCCEEDED_CODE) {
	  return true
	} else {
		if(res.data.errMsg==="请勿重复点赞"){
			return true 
		}else{
			return false
		}
	  
	}
}
/**
 * @description 取消点赞回答的评论
 * @param {number} son_comment_id 评论的id
 * @return {boolean} 成功返回true 失败返回false
 */
export async function cancelLikeAnwserComment(son_comment_id: number) {
	let res = await request({
	  data: {
		modular:'dhy',
		method: 'DELETE',
		group: 'helping',
		action: `unLikeSonComment`,
		data: {
		  son_comment_id
		},
		header: {
		  'content-type': 'application/x-www-form-urlencoded',// 默认值
		},
	  }
	});
	if (res.data.code === REQUEST_SUCCEEDED_CODE) {
	  return true
	} else {
	  return false
	}
}
/**
 * @description 删除回答的评论
 * @param {number} son_comment_id 评论的id
 * @return {boolean} 成功返回true 失败返回false
 */
export async function deleteAnswerComment(son_comment_id: number) {
	let res = await request({
	  data: {
		modular:'dhy',
		method: 'DELETE',
		group: 'helping',
		action: `logicDel`,
		data: {
		 son_comment_id
		},
		header: {
		  'content-type': 'application/x-www-form-urlencoded',// 默认值
		},
	  }
	});
	if (res.data.code === REQUEST_SUCCEEDED_CODE) {
	  return true
	} else {
	  return false
	}
}
/**
 * @description 删除回答评论的回复
 * @param {number} comment_id 回答的id
 * @param {number} son_comment_id 回答评论的回复的id
 * @return {boolean} 成功返回true 失败返回false
 */
export async function deleteAnswerCommentReply(comment_id:number,grantSon_comment_id: number) {
	let res = await request({
	  data: {
		modular:'dhy',
		method: 'DELETE',
		group: 'helping',
		action: `logicDelGrantSon`,
		data: {
			comment_id,
			grantSon_comment_id
		},
		header: {
		  'content-type': 'application/x-www-form-urlencoded',// 默认值
		},
	  }
	});
	if (res.data.code === REQUEST_SUCCEEDED_CODE) {
	  return true
	} else {
	  return false
	}
}